<template>
  <section class="f-goods-add w-card">
    <div class="title-box">
      <span class="title-text">{{ isEdit? '编辑': '新增'}}套餐商品</span>
      <div v-if="!isEdit">
        <el-button @click="reset()">重置</el-button>
        <el-button type="primary" @click="submitHandle('add')">确定创建套餐商品</el-button>
      </div>
      <div v-else>
        <el-button @click="cancelEdit()">取消编辑</el-button>
        <el-button type="primary" @click="submitHandle('modify')">确定重新发布套餐商品</el-button>
      </div>
    </div>

    <section class="f-content">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
        <el-row>
          <el-col :span="7">
            <el-form-item label="设备商品:" prop="wareGoodsId">
              <el-select v-model="ruleForm.wareGoodsId" clearable :disabled="isEdit" @change="getWarehouseGoodsInfo">
                <el-option v-for="(item,index) in warehouseChooseList" :label="item.goodsName" :value="item.wareGoodsId"
                  :key="index" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-form-item label="商品名称:" prop="goodsName">
              <el-input v-model="ruleForm.goodsName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-form-item label="商品状态:" prop="shelveStatus">
              <el-select v-model="ruleForm.shelveStatus" clearable :disabled="isEdit">
                <el-option label="上架" :value="1" />
                <el-option label="下架" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="7">
            <el-form-item label="套餐设备数量:" prop="baseNum">
              <el-input v-model="ruleForm.baseNum" placeholder="请输入套餐设备数量" type="number" />
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-form-item label="购买方式:" prop="buyType">
              <el-select v-model="ruleForm.buyType" clearable :disabled="isEdit" @change="selectBuyType">
                <el-option label="金额购买" :value="1" />
                <el-option label="积分兑换" :value="2" />
                <!-- <el-option label="都可以" :value="3" /> -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-form-item label="购买上限:" prop="buyNumMax">
              <el-input v-model="ruleForm.buyNumMax" placeholder="请输入购买上限" type="number" :disabled="ruleForm.buyType == 1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="7">
            <el-form-item label="排序" prop="sortPower">
              <el-input-number style="width: 100%;" v-model="ruleForm.sortPower" :min="1" :max="100000" placeholder="请输入排序" />
            </el-form-item>
            <el-form-item label="运费方式:" prop="logistType">
              <el-input v-model="ruleForm.logistType" placeholder="请输入运费方式" />
            </el-form-item>
          </el-col>
        </el-row>

        <template v-if="ruleForm.buyType == 1">
          <el-row>
            <el-col :span="7">
              <el-form-item label="标价（元）:" prop="showPrice">
                <el-input v-model="ruleForm.showPrice" placeholder="请输入标价" type="number" />
              </el-form-item>
            </el-col>
            <el-col :offset="1" :span="7">
              <el-form-item label="售价（元）:" prop="actualPrice">
                <el-input v-model="ruleForm.actualPrice" placeholder="请输入售价" type="number" />
              </el-form-item>
            </el-col>
            <el-col :offset="1" :span="7">
              <el-form-item label="采购等级:" prop="vipLevel">
                <el-input v-model="ruleForm.vipLevel" placeholder="请输入0~9，0表示不适用采购等级" type="number" min="0" max="9">
                  <template #append>
                    <p>级</p>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="7">
              <el-form-item label="采购等级有效期:" prop="monthExpire">
                <el-input v-model="ruleForm.monthExpire" placeholder="请输入购买上限" type="number">
                  <template #append>
                    <p>月</p>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <template v-if="ruleForm.buyType == 2">
          <el-row>
            <el-col :span="7">
              <el-form-item label="积分兑换对象:" prop="pointsBuyFromtype">
                <el-select v-model="ruleForm.pointsBuyFromtype" clearable>
                  <el-option label="平台" :value="1" />
                  <el-option label="其他代理商" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :offset="1" :span="7">
              <el-form-item label="购买需要积分:" prop="buyPoints">
                <el-input v-model="ruleForm.buyPoints" placeholder="请输入购买需要积分" type="number" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>

      </el-form>
    </section>

    <div class="f-card" v-if="ruleForm.headImg">
      <p class="f-title">商品信息</p>
      <ul class="f-ul">
        <li style="width: 100%;">
          <p>商品主图：</p>
          <el-image style="width: 100px; height: 100px" :src="ruleForm.headImg" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
            fit="cover" :preview-src-list="[ruleForm.headImg]" />
        </li>
        <li style="width: 100%;">
          <p>商品详情：</p>
          <p v-html="ruleForm.goodsDetail"></p>
        </li>
      </ul>
    </div>
  </section>
</template>
  
<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStateStore } from '@/store'
import Editor from "@tinymce/tinymce-vue";
import api from './api.js'
import { errorDeal, getStore, successDeal } from '@/utils/utils.js';
import axios from 'axios';

export default {
  components: {
    Editor,
  },

  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    goodsInfo: {
      type: Object,
      default: {}
    }
  },

  emits: ["cancelEdit", "baseGoodsModify"],

  setup(props, context) {
    const store = useStateStore()

    const router = useRouter()
    const route = useRoute();

    const ruleFormRef = ref(null)

    const state = reactive({
      ruleForm: {},
      rules: {
        buyPoints: [
          { required: true, message: "请输入购买需要积分", trigger: "blur" },
        ],
        actualPrice: [
          { required: true, message: "请输入商品售价", trigger: "blur" },
        ],
        buyType: [
          { required: true, message: "请选择购买方式", trigger: "change" },
        ],
        pointsBuyFromtype: [
          { required: true, message: "请选择积分兑换对象", trigger: "change" },
        ],
        wareGoodsId: [
          { required: true, message: "请选择设备型号", trigger: "change" },
        ],
        shelveStatus: [
          { required: true, message: "请选择商品状态", trigger: "change" },
        ],
        buyNumMax: [
          { required: true, message: "请输入购买上限", trigger: "blur" },
        ],
        goodsName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        showPrice: [
          { required: true, message: "请输入商品标价", trigger: "blur" },
        ],
        baseNum: [
          { required: true, message: "请输入套餐设备数量", trigger: "blur" },
        ],
        vipLevel: [
          { required: true, message: "请输入采购等级", trigger: "blur" },
        ],
        monthExpire: [
          { required: true, message: "请输入采购等级有效期", trigger: "blur" },
        ],
        sortPower: [
          { required: true, message: '请输入排序', trigger: 'blur' },
        ],
      },

      uploadForm: {
        action: '/ums/file/upload/user/pub',
        headers: {
          Authorization: getStore('USER_AUTHOR_INRE').Authorization || `'','','',3,20,''`,
          Token: `Bearer ${window.localStorage.getItem("USER_TOKEN_INRE")}`,
          platformHeadType: 'rcmsPlatform'
        },
        data: {}
      },

      warehouseChooseList: [],
    })

    onMounted(() => {
      getWarehouseList()
      if (props.isEdit) {
        state.ruleForm = JSON.parse(JSON.stringify(props.goodsInfo))
      }
    })

    function submitHandle(type) {
      ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
          let json = JSON.parse(JSON.stringify(state.ruleForm))
          if (type == 'add') {
            api.goodsCreate(json).then(res => {
              successDeal('新增成功！')
              setTimeout(() => {
                router.go(-1)
              }, 500)
            })
          } else if (type == 'modify') {
            let json = JSON.parse(JSON.stringify(state.ruleForm))
            api.goodsModify(json).then(res => {
              successDeal('编辑成功！')
              context.emit('baseGoodsModify')
            })
          }
        }
      })
    }

    const cancelEdit = () => {
      context.emit('cancelEdit')
    }

    const uploadSuccess = (res) => {
      if (res.code == '200') {
        state.ruleForm.headImg = res.data.ossUrl
        ruleFormRef.value.validate()
      } else {
        errorDeal(res.msg)
      }
    }

    const reset = () => {
      state.ruleForm = {}
      ruleFormRef.value.resetFields()
    }

    const getWarehouseList = () => {
      let json = {
        page: 1,
        size: 100
      }
      api.warehouseList(json).then(res => {
        state.warehouseChooseList = res.data.list
      })
    }

    const getWarehouseGoodsInfo = (wareGoodsId) => {
      let json = {
        uniqueId: wareGoodsId
      }
      api.warehouseGoodsInfo(json).then(res => {
        state.ruleForm = res.data
      })
    }

    const selectBuyType = (e) => {
      if (e == 1) {
        state.ruleForm.buyNumMax = 1
        state.ruleForm.buyPoints = 0
      } else {
        state.ruleForm.monthExpire = 0
        state.ruleForm.vipLevel = 0
      }
    }

    return {
      ...toRefs(state),
      ruleFormRef,
      submitHandle,
      cancelEdit,
      uploadSuccess,
      reset,
      getWarehouseGoodsInfo,
      selectBuyType
    }
  }
}
  </script>
  
<style lang='scss' scoped>
.f-goods-add {
  box-sizing: border-box;
  padding: 20px;
  height: 100%;
  > .title-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30px;
    > .title-text {
      font-size: 16px;
      font-weight: bold;
    }
  }

  .f-content {
    padding-left: 5px;
    .f-title {
      font-weight: bold;
      font-size: 15px;
      color: #000000;
      border-bottom: 1px solid #eaeaea;
      padding-bottom: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .f-tips {
        color: #f73e3e;
        font-size: 12px;
        font-weight: 500;
        margin-left: 40px;
      }
    }
    .f-tabel {
      border: 1px solid #acacac;
      width: 800px;
    }
    .f-guige-box {
      font-size: 14px;
      color: #404040;
      background: #eef2f4;
      display: flex;
      align-items: center;
      padding: 16px 10px;
      margin-top: 20px;
    }
  }

  .f-card {
    background: #f1f4f6;
    border-radius: 6px;
    padding: 20px;
    margin-top: 18px;
    .f-title {
      font-weight: 400;
      font-size: 16px;
      color: #000000;
      margin-bottom: 25px;
      display: flex;
      justify-content: space-between;
    }
    .f-ul {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 15px 0;
      li {
        display: flex;
        width: 50%;
        font-weight: 300;
        font-size: 14px;
        color: #000000;
        p:first-child {
          color: #424242;
          width: 100px;
          text-align: right;
        }
        .f-weight-bold {
          font-weight: bold;
        }
      }
    }
  }
}
</style>

<style>
.f-img-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.f-img-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.f-img-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 125px;
  height: 125px;
  text-align: center;
}
.f-img {
  width: 125px;
  height: 125px;
}
</style>